package cn.zhagzheguo.xk.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import cn.zhagzheguo.xk.config.FileConfig;

/**
 * 对操作file的controller的备份。
 * 
 * @author zhagz
 * 
 */
@Controller
@RequestMapping("/testFile")
public class FileController {

	@RequestMapping("/upload")
	public String showUploadPage() {
		System.out.println("uploading...");
		return "/uploadPage.jsp";
	}

	@RequestMapping(value = "/download/*.*", produces = { "application/*;charset=UTF-8" })
	public void download(HttpServletRequest request, HttpServletResponse response) {

		String sourceName = request.getServletPath();
		System.out.println("sourceName=" + sourceName);// /file/download/65456.doc

		String fileName = sourceName.substring(sourceName.lastIndexOf("/") + 1);

		String absoluteImagePath = FileConfig.FILE_ROOT + fileName;
		System.out.println("download " + absoluteImagePath);
		FileInputStream fis = null;
		OutputStream out = null;

		// 强制改文件名
		// response.setHeader("Content-Disposition", "attachment;filename=" +
		// fileName);

		try {
			out = response.getOutputStream();

			File file = new File(absoluteImagePath);
			fis = new FileInputStream(file);
			byte[] b = new byte[1024];
			int i = 0;

			while ((i = fis.read(b)) > 0) {
				out.write(b, 0, i);
			}
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@RequestMapping("/doUpload")
	public String doUploadFile(@RequestParam("file") MultipartFile file) {
		System.out.println("OriginalFilename:" + file.getOriginalFilename());
		System.out.println("Name:" + file.getName());
		System.out.println("ContentType:" + file.getContentType());
		if (!file.isEmpty()) {
			try {
				FileUtils.copyInputStreamToFile(file.getInputStream(),
						new File(FileConfig.FILE_ROOT + file.getOriginalFilename()));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "jsps/404.jsp";
	}
}
